package com.ruoyi.common.utils;

import com.ruoyi.framework.config.RuoYiConfig;

import java.io.*;
import java.util.UUID;

public class FileUtils {


	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}
	public static void uploadFile(byte[] file, String fileName) throws Exception {
		String filepath =  RuoYiConfig.getProfile();
		File targetFile = new File( RuoYiConfig.getProfile());
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filepath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}



	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}


	/**
	 * 输出指定文件的byte数组
	 *
	 * @param filePath 文件
	 * @return
	 */
	public static void writeBytes(String filePath, OutputStream os) throws IOException
	{
		FileInputStream fis = null;
		try
		{
			File file = new File(filePath);
			if (!file.exists())
			{
				throw new FileNotFoundException(filePath);
			}
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int length;
			while ((length = fis.read(b)) > 0)
			{
				os.write(b, 0, length);
			}
		}
		catch (IOException e)
		{
			throw e;
		}
		finally
		{
			if (os != null)
			{
				try
				{
					os.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
			if (fis != null)
			{
				try
				{
					fis.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
		}
	}
	
	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
